package com.cloudoer.blog.service.impl;

import com.cloudoer.blog.base.BaseService;
import com.cloudoer.blog.exception.ServiceException;
import com.cloudoer.blog.model.Filed;
import com.cloudoer.blog.service.FiledService;
import com.cloudoer.blog.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service(value = "filedService")
public class FiledServiceImpl extends BaseService implements FiledService {
    @Autowired
    private FileUtil fileUtil;

    @Override
    public Filed getById(String id) {
        return filedDao.selectByPrimaryKey(id);
    }

    @Override
    public List<Filed> getByPage(int pstart, int psize) {
        return filedDao.selectByPage(pstart, psize);
    }

    @Override
    public List<Filed> getAll(String filetypeId) {
        return filedDao.selectAll(filetypeId);
    }

    @Override
    public String add(MultipartFile multipartFile, String fileTypeId) throws ServletException, IOException {
        Filed filed = new Filed();
        filed.setId(UUID.randomUUID().toString().replace("-", ""));
        filed.setPostDate(new Date());
        filed.setFileTypeId(fileTypeId);
        filed.setName(multipartFile.getOriginalFilename());
        filed.setSize((double) multipartFile.getSize());
        String url = fileUtil.uploadFile(multipartFile, fileTypeId, filed.getId());
        filed.setUrl(url);
        filedDao.insertSelective(filed);
        return filed.getId();
    }

    @Override
    public int update(Filed filed) {
        return filedDao.updateByPrimaryKeySelective(filed);
    }

    @Override
    public int delete(String id) {
        Filed filed = filedDao.selectByPrimaryKey(id);
        if (filed == null){
            throw new ServiceException("已经删除");
        }
        fileUtil.deleteFileByURL(filed.getUrl());
        return filedDao.deleteByPrimaryKey(id);
    }

    @Override
    public int getCount() {
        return filedDao.selectCount();
    }
}
